<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" lang="zh">
<head th:replace="fragment/globalComponent::commonHead(~{::title},~{},~{::style})">
    <title>GoblinCwl - 首页</title>
    <style>
        .timeStampSHow {
            color: #929e98;
        }

        div {
            overflow-x: hidden;
            overflow-y: auto;
        }

        html {
            position: relative;
            min-height: 100%;
        }

        .web-record {
            position: absolute;
            bottom: 0;
            width: 100%;
        }

        .web-record {
            font-size: 0.8em;
            color: gray;
            margin-top: 4em;
        }

        .web-record p {
            text-align: center;
            font-family: MyHack;
            margin-left: 25em;
        }

        .web-record a {
            color: gray;
        }

        @media (max-width: 768px) {
            .web-record p {
                margin: 0;
            }
        }

        input:focus {
            outline: none;
            border: 0;
            box-shadow: 0 0 0;
        }

        html .console {
            margin-left: 0.5rem;
            /*box-shadow: 0 0 15px 0px rgba(0, 0, 0, 0.35);*/
            box-shadow: -5px 5px 10px -6px rgba(0, 0, 0, 0.35), 5px 0 10px -6px rgba(0, 0, 0, 0.35);
            border: 1px solid black;
            border-top: 0;
        }

        .top {
            text-align: center;
            font-size: 16px;
            padding: 5px;
            background-color: #6ecadc;
            color: white;
            width: 98%;
            float: left;
            margin-left: 0.5rem;
            margin-top: 2rem;
            /*box-shadow: -5px -5px 10px -6px rgba(0, 0, 0, 0.35), 5px 0 10px -6px rgba(0, 0, 0, 0.35);*/
            border: 1px solid #5396a3;
        }

        .top .options {
            font-size: 16px;
            float: right;
        }

        html .console .text {
            font-family: 'MyHack';
            color: #000000;
            font-size: 14px;
            padding: 0.25rem;
        }

        .terminal-console {
            width: 98%;
            float: left;
            height: 33em;
        }

        @media (max-width: 640px) {
            html .console {
                margin-left: 0;
            }

            .terminal-console {
                width: 100%;
            }

            .top {
                width: 100%;
                margin-top: 1rem;
                margin-left: 0;
            }
        }

    </style>
</head>
<body>
<!-- 左侧侧边栏 -->
<div th:replace="fragment/globalComponent::leftSiderBar"></div>


<!-- 页面内容 -->
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
    <div class="content">
        <!-- 顶部导航 -->
        <div th:replace="fragment/globalComponent::topHeader"></div>

        <div class="container-fluid">
            <div class="row">
                <div class="col-lg-6">
                    <!--终端-->
                    <div class="top">
                        <span class="options">○ ○ ⦿</span>
                        <span class="title">GoblinCwl - 终端</span>
                    </div>
                    <div id="terminal-console" class="console terminal-console">
                        <div id="terminalDiv" class="text">
                            <p id="consoleInput">
                                <label id="chatInputLabel" for="chatInput" style="color: #2bd92b">
                                    [<span id="nickName">unAuth</span>@goblincwl.cn] #

                                </label>
                                <input id="chatInput" type="text"
                                       style="background-color:transparent;border:0;outline:none;"
                                       name="t2"
                                       value=""/>
                            </p>
                        </div>
                    </div>
                </div>
                <div class="col-lg-6">
                    <div style="height: 35em;border: 1px solid #6ecadc;margin-top: 2rem">
                        不知道放点啥，好兄弟看到了可以给点建议🤭
                    </div>
                </div>
            </div>


        </div>


    </div>
</div>
<div class="web-record">
    <p>
        © 2021 GoblinCwl 🐉
        <a href="https://beian.miit.gov.cn/" target="_blank">湘ICP备19013886号</a>
    </p>
</div>
</body>
<div th:replace="fragment/globalComponent::commonFoot(~{::script})">
    <script>
        $(function () {
            terminalDataInit();
        });

        const $consoleInput = $("#consoleInput");

        //终端信息初始化
        function terminalDataInit() {
            ajaxHttp({
                type: "GET",
                url: ctx + "/findTerminalData",
                beforeSend: function (request) {
                    insertMessage("<span style='color: #c0a16b'>数据请求中...</span>", 0);
                },
                error: function () {
                    insertMessage("数据请求失败，有空的话麻烦联系下站长处理~", 50);
                },
                success: function (res) {
                    const data = res.data;
                    insertMessage("您是第<span style='color: orange;font-weight: bold'>" + data.accessIpCount + "</span>个访问本站的地址，站点总计已被访问<span style='color: #3c763d;font-weight: bold'>" + data.accessCount + "</span>次。", 50);
                    insertMessage("同一地址超过半小时后再次访问才会进行次数记录。", 100);
                    insertMessage("认证中...", 200);
                    insertMessage("上次访问: <span style='color: grey'>" + data.lastAccessTime + "</span>.", 800);
                    insertMessage("本次访问: <span style='color: dodgerblue'>" + data.accessTime + "</span>.", 800);
                    if (res.data.lastAccessTime === '首次访问') {
                        insertMessage("根据你的环境，我给你取了个名字：<span style='color: #38c0e2;font-weight: bold'>" + data.nickName + "</span>。✔", 850);
                    } else {
                        insertMessage("<span style='color: #38c0e2;font-weight: bold'>" + data.nickName + "</span>，允许访问！✔", 850);
                    }
                    localStorage.setItem("nickName", data.nickName);
                    setTimeout(function () {
                        $("#nickName").text(data.nickName)
                    }, 900);
                    insertMessage("<span style='color: #E74C3C;font-weight: bold'>欢迎来到GoblinCwl的个人网站！</span>", 950);

                    setTimeout(function () {
                        websocketInit()
                    }, 1000)
                },
                successFalse: function (res) {
                    insertMessage(res.msg, 50);
                    insertMessage("数据请求失败，有空的话麻烦联系下站长处理~", 100);
                }
            });
        }

        //websocket初始化
        function websocketInit() {
            var socketUrl;
            if (url.indexOf("https") !== -1) {
                socketUrl = url.replace('https', 'wss') + 'websocket';
            } else {
                socketUrl = url.replace('http', 'ws') + 'websocket';
            }
            const webSocket = new WebSocket(socketUrl);
            webSocket.onerror = function (event) {
                insertMessage("<span style='color: red'>连接发生异常，信息如下：❌</span>");
                insertMessage("<span style='color: red'>" + event.data + "</span>");
                insertMessage("<span style='color: red'>尝试刷新或联系站长处理！❌</span>");
            };
            //与WebSocket建立连接
            webSocket.onopen = function (event) {
                insertMessage("<span style='color: #c0a16b'>正在连接到聊天室...</span>");
            };
            //处理服务器返回的信息
            webSocket.onmessage = function (event) {
                let nowMessage = event.data;
                if (nowMessage.indexOf("{") === 0) {
                    const msgJson = JSON.parse(nowMessage);
                    const time = "<span style='color: #929e98'>[" + msgJson.sendTime + "]</span>";
                    let contentColor = msgJson.color;
                    if (contentColor == null) {
                        contentColor = randomColor();
                    }
                    const message = "<span style='color: " + contentColor + "'>" + msgJson.content + "</span>";
                    $consoleInput.before(time + " " + message + "<br>");
                } else {
                    insertMessage(nowMessage);
                }
                $('#terminal-console').scrollTop($('#terminal-console')[0].scrollHeight);
            };

            function sendMessage(message) {
                //向服务器发送消息
                if (message.indexOf("/login") > 0) {
                    //如果是/login开头，则是管理员登陆
                    let password = message.substr(message.lastIndexOf(" ") + 1);
                    ajaxHttp({
                        type: 'POST',
                        url: ctx + "/manager/login",
                        data: {
                            "password": password
                        },
                        error: function () {
                            insertMessage("<span style='color: red'>登陆异常！❌</span>");
                        },
                        success: function (res) {
                            if (res.code === 200) {
                                //设置Token
                                localStorage.setItem("access_token", res.data);
                                insertMessage("<span style='color: green'>登陆成功！✔</span>");
                                addManagerUl();
                            } else {
                                insertMessage("<span style='color: red'>" + res.msg + "❌</span>");
                            }
                        }
                    })
                } else if (message.indexOf("/logout") > 0) {
                    //登出
                    ajaxHttp({
                        type: 'GET',
                        url: ctx + "/manager/logout",
                        error: function () {
                            insertMessage("<span style='color: red'>登出异常！❌</span>");
                        },
                        success: function (res) {
                            if (res.code === 200) {
                                insertMessage("<span style='color: #acac40'>登出成功！✔</span>");
                                $('#managerLi').remove();
                                document.cookie = "Authorization=null";
                                localStorage.setItem("access_token", "");
                            } else {
                                insertMessage("<span style='color: red'>" + res.msg + "❌</span>");
                            }
                        }
                    })
                } else {
                    webSocket.send(message);
                }
            }

            const $chatInput = $("#chatInput");

            //动态设置输入框的宽度
            $chatInput.width(($("#terminalDiv").width() - $("#chatInputLabel").width()) * 0.9)

            //监听终端点击
            $("#terminal-console").click(function () {
                $chatInput.focus();
            });

            //监听回车
            var time = 0;
            $chatInput.keydown(function (event) {
                const code = event.keyCode;
                //按下回车时
                if (code === 13) {
                    const message = $("#nickName").text() + ': ' + $chatInput.val();
                    //校验信息长度
                    if ($chatInput.val().length > 50) {
                        insertMessage("<span style='color: red'>太多啦，我们还是长话短说吧！🎤</span>")
                    } else if ($chatInput.val().length > 0) {
                        //判断计时器是否处于关闭状态
                        if (time === 0) {
                            time = 10; //设定间隔时间（秒）

                            //启动计时器，倒计时time秒后自动关闭计时器。
                            var index = setInterval(function () {
                                time--;
                                if (time === 0) {
                                    clearInterval(index);
                                }
                            }, 1000);

                            //发送消息
                            sendMessage(message);
                            $chatInput.val('');
                        } else {
                            insertMessage("<span style='color: red'>喝口茶歇歇吧，" + time + "秒就好！☕</span>")
                        }
                    }
                }
            })
        }

        //追加终端信息
        function insertMessage(message, time) {
            const $terminalConsole = $('#terminal-console');
            if (time != null) {
                setTimeout(function () {
                    $consoleInput.before(getMessageTimestamp() + message + "<br>");
                }, time);
            } else {
                $consoleInput.before(getMessageTimestamp() + message + "<br>");
            }
            $terminalConsole.scrollTop($terminalConsole[0].scrollHeight);
        }

        //获取当前时间轴
        function getMessageTimestamp() {
            return "<span class='timeStampSHow'>"
                + "["
                + new Date().Format("HH:mm:ss")
                + "] "
                + "</span>";
        }
    </script>
</div>
</html>